package com.example.content.activity

import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.example.content.R
import com.example.content.adapter.recycle.BindListener
import com.example.content.adapter.recycle.RecyclerAdapter
import com.example.content.adapter.recycle.entity.ItemEntity
import com.example.content.databinding.ActivitySearchBinding
import com.example.content.fragment.search.SearchFragment
import com.example.content.manager.GlobalMgr
import com.example.content.viewmodule.search.SearchViewModel
import com.example.core.utils.SpanUtils
import kotlinx.android.synthetic.main.fragment_home.*

class SearchActivity:  BaseActivity<ActivitySearchBinding, SearchViewModel>() {

    var searchKey = ""
    private var isAttach = false
    /**
     * 标记是否搜索过一次，搜索过就让他显示结果页fragment
     */
    private var isSearched = false;

    lateinit var keyAdapter: RecyclerAdapter<String>

    override fun initView() {
        keyAdapter = RecyclerAdapter(object : BindListener<String> {
            override fun convert(holder: BaseViewHolder, item: ItemEntity<String>) {
                val textView = holder.getView<TextView>(R.id.search_key)
                if (!TextUtils.isEmpty(item.data)) {
                    val string = SpanUtils.matchSearchText(
                        ContextCompat.getColor(this@SearchActivity, R.color.colorAccent),
                        item.data, searchKey
                    )
                    textView.text = string
                } else {
                    textView.text = item.data
                }
            }
        })
        keyAdapter.addItemView(R.layout.search_key_item_layout)
        dataBinding.keyRecycler.adapter = keyAdapter
        dataBinding.keyRecycler.layoutManager = LinearLayoutManager(this)


    }

    override fun initListener() {
        dataBinding.backBtn.setOnClickListener {
            finish()
        }
        dataBinding.searchContent.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                //方式点击关键词后，还联想显示关键词列表
                if (isAttach) {
                    isAttach = false
                    return
                }
                searchKey = dataBinding.searchContent.text.toString()
                if (TextUtils.isEmpty(searchKey)) {
                    dataBinding.clearSearchContent.visibility = View.INVISIBLE
                    keyAdapter.updateData(emptyList())
                } else {
                    dataBinding.clearSearchContent.visibility = View.VISIBLE
                    viewModel.getSearchKey(searchKey)
                }
            }

            override fun afterTextChanged(s: Editable?) {

            }
        })
        dataBinding.search.setOnClickListener {
            if (!TextUtils.isEmpty(searchKey)) {
                GlobalMgr.searchKey.postValue(searchKey)
                showResultPage()
                keyAdapter.updateData(emptyList())
            }
        }
        dataBinding.clearSearchContent.setOnClickListener {
            dataBinding.searchContent.text = null
        }
        viewModel.searchKeys.observe(this, observer = { list ->
            keyAdapter.updateData(list.map {
                ItemEntity(data = it)
            })
        })


        keyAdapter.setOnItemClickListener { _, _, position ->
            val textValue = keyAdapter.getItem(position).data
            if (!TextUtils.isEmpty(textValue)) {
                isAttach = true
                dataBinding.searchContent.setText(textValue)
                searchKey = textValue
                GlobalMgr.searchKey.postValue(textValue)
                showResultPage()
            }
            keyAdapter.updateData(emptyList())
        }
    }

    private fun showResultPage() {
        if (!isSearched) {
            isSearched = true
            supportFragmentManager.beginTransaction()
                .replace(R.id.container, SearchFragment(), SearchFragment::class.java.simpleName)
                .commitAllowingStateLoss()
        }
    }

    override fun initData() {

    }

    override fun getLayoutId() = R.layout.activity_search
}